package cn.tedu.zx.sso.security.service.user;

import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.pojo.users.entity.User;
import cn.tedu.zx.sso.mapper.user.UserMapper;
import cn.tedu.zx.sso.pojo.entity.UserUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserSSOUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = null;
        try {
            user = userMapper.findByUsername(username);
            log.debug("搜索：{}",user);
        } catch (ServiceException e) {
            throw new BadCredentialsException("登录失败，用户名不正确！");
        }
        if (user==null) {
            return null;
        }
        log.debug("启用：{}",user.getIsEnable());
        if (user.getIsEnable()!=1){
            throw new BadCredentialsException("登录失败，用户账号已经被禁用！");
        }
        UserUserDetails userDetails=new UserUserDetails();
        BeanUtils.copyProperties(user,userDetails);
        //返回
        return userDetails;
    }
}
